package tongbu方法;

import java.util.concurrent.locks.ReentrantLock;

public class test2 {
        public static void main(String[] args) {

            tongbufangfa2 tb = new tongbufangfa2();
            Thread t1 = new Thread(tb,"A线程");
            Thread t2 = new Thread(tb,"B线程");
            Thread t3 = new Thread(tb,"C线程");
            t1.start();
            t2.start();
            t3.start();
        }
    }

    class tongbufangfa2 implements Runnable{
        private int ticket = 5000;
        private  ReentrantLock rt = new ReentrantLock(); // 需要挂到私有属性里，一开始是挂载每次循环都创建。 -- 就相当于无锁。
        @Override
        public void run() {
            while (true){

                try {
                    rt.lock();
                    if(ticket <=0){
//                        rt.unlock();// 最后需要break的时候，结束上锁。 不然到了break就跳过，不会执行下面的代码了。
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "第" + ticket + "张牌");
                    ticket--;
                } finally {
                    rt.unlock();
                }


            }
        }


    }
